import 'dart:convert';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_elder/models/elder_grid_entity.dart';
import 'package:ls_work/a_elder/page/elder_info_page.dart';
import 'package:ls_work/a_yyt/models/medical_elder_entity.dart';
import 'package:ls_work/a_yyt/models/staff_group_entity.dart';
import 'package:ls_work/a_yyt/page/add_sporadic_ncome_page.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/ui/select_old_page.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/event_bus.dart' as e;
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/function_grid_widget.dart';
import 'package:ls_work/widgets/load_image.dart';

import '../../ui/elder_detail_info_page.dart';

class ElderGridPage extends StatefulWidget {
  final int? type;
  final bool isSelected;
  final bool needBack;
  final bool search;

  ElderGridPage(
      {Key? key,
      this.type,
      this.isSelected = false,
      this.needBack = false,
      this.search = false});

  @override
  _ElderGridPageState createState() => _ElderGridPageState();
}

class _ElderGridPageState extends State<ElderGridPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  List<ElderGridFloorEntity> dataList = [];

  int? _buildingId ;
  int? _floorId ;
  double _ageBegainValue = 0;
  double _ageEndValue = 120;
  bool _sexManSelected = false;
  bool _sexWemanSelected = false;
  List<StaffGroupInfo> _nurseLevelList = [];
  List<StaffGroupInfo> _bodyTypeList = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (!widget.search) {
        // _fectData(widget.type);
      }
    });

    e.eventBus.on(Constant.eventElderFilter, (arg) {
      List temp = arg;
      _buildingId = temp.first;
      _floorId = temp.last;
      _fectData(widget.type??0);
    });
    e.eventBus.on(Constant.eventElderRightFilter, (arg) {
      List temp = arg;
      _ageBegainValue = temp[0];
      _ageEndValue = temp[1];
      _sexManSelected = temp[2];
      _sexWemanSelected = temp[3];
      _nurseLevelList = temp[4];
      _bodyTypeList = temp[5];
      _fectData(widget.type??0);
    });

    e.eventBus.on("refreshElder", (arg){
      _fectData(widget.type??0);
    });


  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        backgroundColor: Colours.bg_color,
        body: dataList.length <= 0
            ? Gaps.emptyContainer
            : ListView.builder(
                itemBuilder: (context, position) {
                  return ListView.builder(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      return Column(
                        children: [
                          Container(
                            width: double.infinity,
                            height: 50,
                            margin: EdgeInsets.only(left: 20, right: 20),
                            padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              '${dataList[position].buildingNo}-${dataList[position].elderFloorBeanList![index].floorNo}',
                              style: TextStyles.textDark18,
                            ),
                          ),
                          _cell(position,index),
                          Container(height: 10,),
                        ],
                      );
                    },
                    itemCount: (dataList[position].elderFloorBeanList??[]).length,
                  );
                },
                itemCount: dataList.length,
              )
        // : FlutterTableView(
        //     sectionCount: dataList.first.elderFloorBeanList.length,
        //     rowCountAtSection: (section) => 1,
        //     sectionHeaderBuilder: (context, section) {
        //       return Container(
        //         width: double.infinity,
        //         height: 50,
        //         margin: EdgeInsets.only(left: 20, right: 20),
        //         padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
        //         alignment: Alignment.center,
        //         decoration: BoxDecoration(
        //           color: Colors.white,
        //           borderRadius: BorderRadius.circular(8),
        //         ),
        //         child: Text(
        //           '${dataList.first.elderFloorBeanList[section].floorNo}',
        //           style: TextStyles.textDark18,
        //         ),
        //       );
        //     },
        //     cellBuilder: (context, section, row) {
        //       return dataList.length <= 0 ? Container() : _cell(section, row);
        //     },
        //     sectionHeaderHeight: (context, section) => 50,
        //     cellHeight: (context, section, row) {
        //       int crossCount =
        //           MediaQuery.of(context).orientation == Orientation.landscape
        //               ? 6
        //               : 4;
        //       return ((ScreenUtil.getScreenW(context) - 50) /
        //                       crossCount *
        //                       10 /
        //                       9 +
        //                   10) *
        //               (dataList.first.elderFloorBeanList[section]
        //                           .customerElderBeanList.length /
        //                       crossCount)
        //                   .ceil() + 70;
        //     },
        //   ),
        );
  }

  Widget _cell(
    int position,int section,
  ) {

    return FunctionGridColumn(
        // maxCrossAxisExtent: 150,
        // MediaQuery.of(context).orientation == Orientation.landscape
        count:
            MediaQuery.of(context).orientation == Orientation.landscape ? 5 : 3,
        crossSpace: 10.0,
        mainSpace: 10.0,
      // itemCount: (dataList[position].elderFloorBeanList![section].customerElderBeanList??[]).length,
      // padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
      children: List.generate((dataList[position].elderFloorBeanList![section].customerElderBeanList??[]).length, (index){
        var item =  (dataList[position].elderFloorBeanList![section].customerElderBeanList??[])[index];
        return InkWell(
          onTap: () {
            if (widget.needBack) {
              Navigator.pop(
                  context,
                  dataList[position].elderFloorBeanList![section]
                      .customerElderBeanList![index]);
              return;
            }
            if (widget.isSelected) {
              Navigator.pushReplacement(context,
                  new MaterialPageRoute(builder: (BuildContext context) {
                    return AddHomeSporadicIncomePage(
                      type: 0,
                      elderInfo: dataList[position].elderFloorBeanList![section]
                          .customerElderBeanList![index],
                    );
                  }));
            } else {
              // AppNavigator.push(
              //   context,
              //   ElderInfoPage(
              //     customerId: dataList[position].elderFloorBeanList![section]
              //         .customerElderBeanList![index].id!,
              //   ),
              // );
              Go().push(ElderDetailInfoPage(customerId: dataList[position].elderFloorBeanList![section]
                  .customerElderBeanList![index].id!,));
            }
            //       },
          },
          child: newOldContent(MedicalElderInfo.fromJson(item.toJson())),
        );
      }),
      // itemBuilder: (context, index) {
      //   var item =  (dataList[position].elderFloorBeanList![section].customerElderBeanList??[])[index];
      //
      // },
    ).addToContainer(padding: EdgeInsets.fromLTRB(10, 10, 10, 0));
  }

  // Future _onRefresh() async {
  //   _page = 1;
  //   await _fectData(widget.type);
  // }

  Future _fectData(int type) async {
    Map<String, dynamic> _map = {};
    if (widget.type == 0) {
      _map["statusSecondId"] = 0;
    } else if (widget.type == 1) {
      _map["statusSecondId"] = 1;
    }
    if (_buildingId!=null&&_buildingId! > 0) {
      _map["buildingId"] = _buildingId;
    }
    if (_floorId!=null&&_floorId! > 0) {
      _map["floorId"] = _floorId;
    }

    if (_ageBegainValue > 0) {
      _map["ageStart"] = _ageBegainValue;
    }
    if (_ageEndValue > 0) {
      _map["ageEnd"] = _ageEndValue;
    }

    if (_sexManSelected && _sexWemanSelected) {
      _map["sexes"] = "0,1";
    } else if (_sexManSelected) {
      _map["sexes"] = "0";
    } else if (_sexWemanSelected) {
      _map["sexes"] = "1";
    }


    var nurseList = [];
    for (var item in _nurseLevelList) {
      if (item.isSelected==true) {
        nurseList.add(item.id);
      }
    }
    if (nurseList.length > 0) {
      _map["nurseLevelIds"] = nurseList.join(",");
    }



    var bodyList = [];
    for (var item in _bodyTypeList) {
      if (item.isSelected==true) {
        bodyList.add(item.id);
      }
    }
    if (bodyList.length > 0) {
      _map["healths"] = bodyList.join(",");
    }

    if(GlobalConfigs.elderUseFilter){
      if(_map.length<=2){
        var ids = GlobalConfigs.savedFilterElder.map((e)=>e.id).join(",");
        _map['customerIdStr'] = ids;
      }
    }
    print(_map);
    String url = HttpApi.getCustomerElderBuildingBeans;
    if (_map.isNotEmpty) {
      url += "?${requestParams(_map)}";
    }
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(url).then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            ElderGridEntity model = ElderGridEntity.fromJson(map);
            dataList.clear();
            if ((model.data??<ElderGridFloorEntity>[]).length > 0) {
              for(var item in (model.data??<ElderGridFloorEntity>[])){
                for(var old in item.elderFloorBeanList??<ElderGridFloorElderEntity>[]){
                  (old.customerElderBeanList??[]).sort((o1,o2){
                    return (o1.roomNo??"").compareTo((o2.roomNo??""));
                  });
                }
              }
              setState(() {
                dataList = model.data??[];
              });
            } else {
              Toast.show(map["msg"]);
            }
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
        // view.provider.setHasMore(false);
      }
    }).catchError((e) {
      page.closeProgress();
      // view.provider.setHasMore(false);
      Toast.show(getErrorMessage(e));
    });
  }
}
